<template>
  <div>
    <h3>{{isCreate ? '创建' : '编辑'}}课程</h3>

    <ele-form
      v-model="data"
      :form-desc="fields"
      :request-fn="submit"
    ></ele-form>
  </div>
</template>

<script lang="ts">
  import {Component, Prop, Vue} from 'vue-property-decorator'

  interface IField {
    name: any;
    cover: any;
  }

  @Component({})
  export default class CoursesList extends Vue {
    // props 属性用@Prop()装饰器进行装饰
    @Prop(String) id?: string

    // computed 计算属性使用
    // data选项中的属性直接定义
    data = {}
    fields = {
      name: {
        label: '课程名称',
        type: 'input'
      },
      cover: {
        label: '课程封面图',
        type: 'input'
      }
    }

    // 带有get前缀的函数表示
    get isCreate() {
      return !this.id
    }

    /**
     * 钩子函数和普通函数直接写在类中
     */
    async submit(data: any) {
      const url = this.isCreate ? '/courses' : `/courses/${this.id}`
      const method = this.isCreate ? 'post' : 'put'
      await this.$http[method](url, data)
      this.$message.success('保存成功')
      this.data = { }
      this.$router.go(-1)
    }

    async fetch() {
      const res = await this.$http.get(`/courses/${this.id}`)
      this.data = res.data
    }

    created() {
      !this.isCreate && this.fetch() // 是编辑操作时执行fetch操作
    }
  }
</script>

<style scoped>

</style>
